/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { getAlignTarget, hvigorCore } from '@ohos/hvigor';
import { DefaultTargetConst } from '../const/common-const.js';
import { ProjectModel } from '../model/project/project-model.js';
import { InjectUtil } from "./inject-util.js";
import { ModuleBuildProfile } from '../options/build/module-build-profile.js';

export class TargetUtils {
  // 对target优先级进行整理，用于target筛选
  static pushTryTargets(params: { projectModel: ProjectModel; moduleName: string; superTargetName: string }): string[] {
    const tryTargets = [];
    const specificTarget = params.projectModel.getModuleSpecificTargets().get(params.moduleName)?.[0];
    if (InjectUtil.isOhosTest() || InjectUtil.isLocalTest()) {
      if (specificTarget === DefaultTargetConst.OHOS_TEST_TARGET) {
        tryTargets.push(DefaultTargetConst.OHOS_TEST_TARGET);
        return tryTargets;
      }

      tryTargets.push(DefaultTargetConst.DEFAULT_TARGET);
      return tryTargets;
    }

    // 优先级1 align target
    if (getAlignTarget()) {
      tryTargets.push(getAlignTarget()!);
    }
    // 优先级2 命令行指定的target
    if (specificTarget && specificTarget !== DefaultTargetConst.ALL_TARGET) {
      tryTargets.push(specificTarget);
    }
    // 优先级3 父级target
    tryTargets.push(params.superTargetName);
    // 优先级4 fallback target
    tryTargets.push(...this.getFallbackTargets(), DefaultTargetConst.DEFAULT_TARGET);
    return tryTargets;
  }

  // 打app包时筛选targets
  static computeTargets(specificTargets: any, optionTargets: ModuleBuildProfile.ModuleTargetBuildOpt[]): string[] {
    const targets = specificTargets ?? ['all'];

    const alignTarget = getAlignTarget();
    // 当alignTarget不存在，或者目前正在跑ohosTest&localTest，走原有逻辑
    if (!alignTarget || InjectUtil.isLocalTest() || InjectUtil.isOhosTest()) {
      return targets;
    }

    const hasAlignTarget = optionTargets.some((opt) => opt.name === alignTarget);
    // 命中alignTarget直接返回
    if (hasAlignTarget) {
      return [alignTarget];
    }

    // 没有命中alignTarget找fallbackTarget
    const fallbackTargets = this.getFallbackTargets();
    for (const fallbackTarget of fallbackTargets) {
      const hasFallbackTarget = optionTargets.some((opt) => opt.name === fallbackTarget);
      if (hasFallbackTarget) {
        return [fallbackTarget];
      }
    }

    // 都没有命中返回default
    return ['default'];
  }

  // 获取fallbackTargets
  static getFallbackTargets(): string[] {
    const fallbackTargets = hvigorCore.getParameter().getProperty(DefaultTargetConst.FALLBACK_TARGET);
    if (!fallbackTargets) {
      return [];
    }
    if (typeof fallbackTargets === 'string') {
      return fallbackTargets.split(',');
    }
    return fallbackTargets;
  }
}
